package org.charry.lib.commons.string;

/**
 * A utility class for common string manipulation.
 * 
 * @author wcharry
 * 
 */
public final class StringUtility {
	/**
	 * Dummy constructor.
	 */
	private StringUtility() {
		// NOOP
	}

	public static void main(String[] args) {
		System.out.println(escapeSQL("Bill's firm and \\ k"));
		System.out.println(toUnixPath("c:\\temp/new foler"));
		System.out.println(toUnixPath("c:\\temp/new foler", true));
		System.out.println(toUnixPath("C:\\temp\\c\\new files\\"));
		System.out.println(toUnixPath("C:\\temp\\c\\new files", true));
		System.out.println(toWindowsPath("C:/a/b/c", false));
	}

	/**
	 * Escape a SQL string.
	 * 
	 * @param sql
	 *            input SQL
	 * @return escaped SQL
	 */
	public static String escapeSQL(final String sql) {
		return sql.replace("'", "''").replace("\\", "\\\\");
	}

	/**
	 * Convert path from Windows style to Unix style.
	 * 
	 * @param path
	 *            Windows style path
	 * @return Unix style path
	 */
	public static String toUnixPath(final String path) {
		return toUnixPath(path, false);
	}

	/**
	 * Convert path from Windows style to Unix style.
	 * 
	 * @param path
	 *            Windows style path
	 * @param addTrailingSlash
	 *            if true, add a trailing slash
	 * @return Unix style path
	 */
	public static String toUnixPath(final String path,
			final boolean addTrailingSlash) {
		String newPath = path.replace("\\", "/");

		if (addTrailingSlash && !newPath.endsWith("/")) {
			newPath += "/";
		}

		return newPath;
	}

	/**
	 * Convert path from Unix style to Windows style.
	 * 
	 * @param path
	 *            Unix style path
	 * @return Windows style path
	 */
	public static String toWindowsPath(final String path) {
		return toWindowsPath(path, false);
	}

	/**
	 * Convert path from Unix style to Windows style.
	 * 
	 * @param path
	 *            Unix style path
	 * @param addTrailingSlash
	 *            if true, add a trailing backslash
	 * @return Windows style path
	 */
	public static String toWindowsPath(final String path,
			final boolean addTrailingSlash) {
		String newPath = path.replace("/", "\\");

		if (addTrailingSlash && !newPath.endsWith("\\")) {
			newPath += "\\";
		}

		return newPath;
	}
}
